﻿using System;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.UI.HtmlControls;

namespace Library.WebControls.SimpleDateEdit {
	[ToolboxBitmap(typeof(SpDateEdit), "Library.WebControls.SimpleDateEdit.SpDateEdit.bmp")]
	[Designer(typeof(SpDateEditDesign))]
	[SupportsEventValidation]
	[ToolboxData("<{0}:SpDateEdit runat=server></{0}:SpDateEdit>")]
	[DesignTimeVisible(true)]
	public class SpDateEdit : BaseAjaxControl, IEffectControl {
		public SpDateEdit() {
			//TodayText = "Today";
			//ClearText = "Clear";
			ClientScript = new ClientScript();
		}
		protected static Type SpDateEditType = typeof(SpDateEdit);
		public const string CssFile = "spdateedit-ui.css";
		protected override string StyleSheetFileName {
			get { return CssFile; }
		}

		private TextBox _txtText;
		private HiddenField _hfValue;
		private HtmlGenericControl _divCalendar;
		protected override void CreateChildControls() {
			_divCalendar = new HtmlGenericControl("div");
			_divCalendar.Attributes["class"] = "spDateEdit";
			_txtText = new WebTextEdit { Width = new Unit("100%"), CssClass = "spDateEditText" };
			_hfValue = new HiddenField();
			var div = new HtmlGenericControl("div");
			div.Attributes["class"] = "spDateEditBorder";
			_divCalendar.Controls.Add(div);
			div.Controls.Add(_txtText);
			div.Controls.Add(_hfValue);
			Controls.Add(_divCalendar);
		}
		//[Description("Provides access to an SimpleGridView's edit template form.")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[Category("Data")]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		[DefaultValue("")]
		public ClientScript ClientScript { private set; get; }
		public override bool ClientEnable {
			get {
				return base.ClientEnable;
			}
			set {
				base.ClientEnable = value;
				EnsureChildControls();
				if (value) {
					_divCalendar.Attributes["class"] = "spDateEdit";
				} else {
					_divCalendar.Attributes["class"] = "spDateEditDisable";
				}
			}
		}
		public Unit Width {
			get {
				EnsureChildControls();
				return new Unit(_divCalendar.Style[HtmlTextWriterStyle.Width]);
			}
			set {
				EnsureChildControls();
				_divCalendar.Style[HtmlTextWriterStyle.Width] = value.ToString();
			}
		}

		private string _displayFormat = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern;

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			if (IncludeScriptOnLoad(SpDateEditType, "DateEdit", "Library.WebControls.SimpleDateEdit.include.SpDateEdit.js", EffectLib)) {
				System.Globalization.DateTimeFormatInfo df = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat;
				string[] sds = df.AbbreviatedDayNames;
				var culteralDate = new StringBuilder();
				culteralDate.AppendFormat("_SPShortDay=['{0}','{1}','{2}','{3}','{4}','{5}','{6}'];", sds[0], sds[1], sds[2], sds[3], sds[4], sds[5], sds[6]);
				sds = df.DayNames;
				culteralDate.AppendFormat("_SPDay=['{0}','{1}','{2}','{3}','{4}','{5}','{6}'];", sds[0], sds[1], sds[2], sds[3], sds[4], sds[5], sds[6]);

				string[] sms = df.AbbreviatedMonthNames;
				culteralDate.AppendFormat("_SPShortMon=['{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}'];", sms[0], sms[1], sms[2], sms[3], sms[4], sms[5], sms[6], sms[7], sms[8], sms[9], sms[10], sms[11]);
				sms = df.MonthNames;
				culteralDate.AppendFormat("_SPMon=['{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}'];", sms[0], sms[1], sms[2], sms[3], sms[4], sms[5], sms[6], sms[7], sms[8], sms[9], sms[10], sms[11]);
				culteralDate.AppendFormat("_SPAMPM=['{0}','{1}'];", df.AMDesignator, df.PMDesignator);
				Page.ClientScript.RegisterClientScriptBlock(SpDateEditType, "DateEditSC", culteralDate.ToString(), true);

				AddLinkCssControl(CssFileName);
			}
		}

		public override string ID {
			get {
				EnsureChildControls();
				return _txtText.ID;
			}
			set {
				EnsureChildControls();
				_txtText.ID = value;
				_hfValue.ID = String.Format("{0}_v", value);
			}
		}


		public string DisplayFormat {
			get {
				return _displayFormat;
			}
			set {
				EnsureChildControls();
				_displayFormat = value;
				DateTime dt = Date;
				_txtText.Text = dt != DateTime.MinValue ? Date.ToString(value) : String.Empty;
			}
		}

		public DateTime Date {
			get {
				EnsureChildControls();
				if (String.IsNullOrEmpty(_hfValue.Value)) {
					return DateTime.MinValue;
				}


				if (!String.IsNullOrEmpty(_hfValue.Value)) {
					string[] ps = _hfValue.Value.Split('|');
					if (ps.Length == 6) {
						var day = new int[6];
						for (int i = 0; i < day.Length; i++) {
							if (!Int32.TryParse(ps[i], out day[i])) {
								return DateTime.MinValue;
							}
						}

						return new DateTime(day[0], day[1] + 1, day[2], day[3], day[4], day[5]);
					}
				}


				return DateTime.MinValue;
			}

			set {
				EnsureChildControls();
				if (value == DateTime.MinValue) {
					_hfValue.Value = String.Empty;
					_txtText.Text = String.Empty;
				} else {
					_hfValue.Value = String.Format("{0}|{1}|{2}|{3}|{4}|{5}", value.Year, value.Month - 1, value.Day, value.Hour, value.Minute, value.Second);
					_txtText.Text = value.ToString(DisplayFormat);
				}
			}
		}
		[Description("Text box for date edit")]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		[MergableProperty(false)]
		[Category("Data")]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
		[DefaultValue("")]
		public WebControl TextEdit {
			get {
				EnsureChildControls();
				return _txtText;
			}
		}

		public DateTime? DateValue {
			get {
				DateTime date = Date;
				if (date == DateTime.MinValue) return null;
				return date;
			}
			set {
				Date = !value.HasValue ? DateTime.MinValue : value.Value;
			}
		}

		public override bool ClientVisible {
			get {
				return base.ClientVisible;
			}
			set {
				base.ClientVisible = value;
				EnsureChildControls();
				if (value) {
					_divCalendar.Style.Remove(HtmlTextWriterStyle.Display);
				} else {
					_divCalendar.Style[HtmlTextWriterStyle.Display] = "none";
				}
			}
		}

		protected override void CreateClientObjectAtRender(HtmlTextWriter writer) {

			BeginScriptTag(writer);

			writer.Write(String.Format("var {0}=new SpDateEdit('{0}', '{1}', '{2}', '{3}', {4}, {5}, '{6}', {7}, {8}, '{9}', '{10}');",
				ClientName,
				_txtText.ClientID,
				_hfValue.ClientID,
				(Int32)DisplayEffect,
				TimeEffect,
				StepEffect,
				DisplayFormat,
				ClientEnable.ToString().ToLower(),
				ClientVisible.ToString().ToLower(),
				HttpContext.Current.Server.HtmlEncode(TodayText),
				HttpContext.Current.Server.HtmlEncode(ClearText)
				));

			AddScriptHandler(writer, 1, ClientScript.DateChanged, "AddHandler");
			AddScriptHandler(writer, 2, ClientScript.HideComplete, "AddHandler");
			EndScriptTag(writer);
		}

		protected override void Render(HtmlTextWriter writer) {
			if (!Visible)
				return;
			if (String.IsNullOrEmpty(TodayText)) {
				var basePage = Page as BasePage;
				if (basePage != null) {
					TodayText = basePage.CulText.Today;
					if (String.IsNullOrEmpty(ClearText)) {
						ClearText = basePage.CulText.Clear;
					}
				}
			}

			if (String.IsNullOrEmpty(_displayFormat)) {
				_displayFormat = System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern;
			}
			//_txtText.CssClass = ClientEnable ? "calenderEnableText" : "calenderDisableText";
			_txtText.Attributes["onblur"] = ClientName + ".Call(1)";
			_txtText.Attributes["onclick"] = ClientName + ".Call(2)";
			_txtText.Attributes["onkeypress"] = "return " + ClientName + ".Call(3, event)";
			//if (!ClientVisible) {
			//  _txtText.Style.Add(HtmlTextWriterStyle.Display, "none");
			//}
			//writer.Write("<div>");
			base.Render(writer);
			//writer.Write("</div>");
		}

		public string TodayText { get; set; }

		public string ClearText { get; set; }

		private Effect _displayEffect = Effect.Normal;
		public Effect DisplayEffect {
			get { return _displayEffect; }
			set { _displayEffect = value; }
		}

		private int _timeEffect = 5;
		public int TimeEffect {
			get { return _timeEffect; }
			set { _timeEffect = value; }
		}

		private int _stepEffect = 1;
		public int StepEffect {
			get { return _stepEffect; }
			set { _stepEffect = value; }
		}




	}
}
